package com.iris.serializable;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 项目: thinking
 * 包名: com.iris.serializable
 * 作者: victor
 * 日期: 2016年11月15日
 * 说明: SerializableTest
 */
public class SerializableTest {
	
	public <T> void serializable(T cls) throws IOException{

		String dir=cls.getClass().getResource("").getPath()+cls.getClass().getSimpleName()+".io";
		System.out.println(dir);
//		System.out.println("1:" + Thread.currentThread().getContextClassLoader().getResource(""));  
//		System.out.println("2:" + SerializableTest.class.getClassLoader().getResource(""));  
//		System.out.println("3:" + ClassLoader.getSystemResource(""));  
//		System.out.println("4:" + SerializableTest.class.getResource(""));//IdcardClient.class文件所在路径  
//		System.out.println("5:" + SerializableTest.class.getResource("/")); // Class包所在路径，得到的是URL对象，用url.getPath()获取绝对路径String  
//		System.out.println("6:" + new File("/").getAbsolutePath());  
//		System.out.println("7:" + System.getProperty("user.dir"));  
//		System.out.println("8:" + System.getProperty("file.encoding"));//获取文件编码  
		ByteArrayOutputStream bos = new ByteArrayOutputStream();  
		ObjectOutputStream os = new ObjectOutputStream(bos);  
		os.writeObject(cls);  
		os.flush();  
		os.close();  
		byte[] b = bos.toByteArray();  
		System.out.println(new String(b));
		bos.close();  
		  
		FileOutputStream fos = new FileOutputStream(dir);  
		fos.write(b);  
		fos.close();  
	
	}
	
	public <T> T getObj(T cls) throws Exception{
		String path = this.getClass().getResource("")+cls.getClass().getSimpleName()+".io";
		path= path.replaceFirst("file:/", "");
		System.out.println(path);
		FileInputStream fis = new FileInputStream(path);  
		ObjectInputStream ois = new ObjectInputStream(fis);  
		T bean = (T) ois.readObject();  
		ois.close();  
		fis.close(); 
		return bean;
	}
	
	public static void main(String[] args) throws Exception {
		SerializableTest ser = new SerializableTest();
//		ser.serializable(new BeanInterfaceImpl());
		BeanTest bean =new BeanTest();
		bean.setCount(88);
		bean.setStr("88888888");
		ser.serializable(bean);
		bean =ser.getObj(bean);
		System.out.println(bean.getCount()+"=="+bean.getStr());
	}
}
